<template>
  <div class="environment-info">
    <CardBox title="生境观测" :showTab="true" :tabs="tabs" :tabItemIsActive="tab.id" @tab-change="handleTabChange"></CardBox>
    <div class="content-container">
      <div class="env-layout">
        <!-- 左侧大数据 -->
        <div class="env-main">
          <div class="env-chart" ref="airQualityChart"></div>
          <div class="env-chart-content">
            <div class="air-value">{{AQI}}</div>
            <div class="air-level">{{Quality}}</div>
          </div>
          <div class="env-footer">
            <div class="env-title">空气质量指数</div>
            <div class="air-time">更新时间：{{ updateTime }}</div>
          </div>
        </div>
        <!-- 右侧小数据 -->
        <div class="env-grid">
          <div class="env-item" v-for="(item, index) in results" :key="index">
            <div class="item-content">
              <span class="item-icon" v-if="index<6">
                <img :src="require(`@/assets/img/env-tem-${index + 1}.png`)" alt=""/>
              </span>
              <span class="env-label">{{ item.pointName }}</span>
              <div class="env-value">{{ item.pointValue +(item.pointUnit?item.pointUnit:"")}}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import * as echarts from "echarts";
import CardBox from "@/components/Global/CardBox.vue";
import { EventBus } from "../../utils/event-bus";
let that;
export default {
  name: "EnvironmentInfo",
  components: {
    CardBox,
  },
  data() {
    return {
      updateTime: "",
      timer: null,
      sample: null,
      AQI:"",
      Quality:"",
      tab: {
        id: "qixiang",
        name: "气象",
      },
      tabs: [
        {
          id: "qixiang",
          name: "气象",
        },
        {
          id: "turang",
          name: "土壤",
        }
      ],
      airQualityChart: null,
      results: {
        time: "",
      },
    };
  },
  mounted() {
    this.timer = setInterval(function () {
      that.getData("空气");
    }, 60000);
    this.$nextTick(() => {
      this.initAirQualityChart();
    });
  },
  created() {
    that = this;
    EventBus.$on("sent-device-id-to-right", (message) => {
      this.sample = message;
      this.getData(this.tab.name);
    });
    EventBus.$on("tab-click", (message) => {
      this.tab = message;
      this.getData(this.tab.name);
    });
  },
  beforeDestroy() {
    if (this.airQualityChart) {
      this.airQualityChart.dispose();
      this.airQualityChart = null;
    }
    if (this.timer !== null) {
      clearInterval(this.timer);
      this.timer = null; // 确保定时器引用被清除，防止内存泄漏
    }
  },
  methods: {
    getData(type) {
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = currentDate.getMonth() + 1; // 月份从0开始，需要加1
      const day = currentDate.getDate();
      const hours = String(currentDate.getHours()).padStart(2, "0");
      const minutes = String(currentDate.getMinutes()).padStart(2, "0");
      const seconds = String(currentDate.getSeconds()).padStart(2, "0");
      this.updateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      this.$api.sample.getItemList(this.sample.id, type).then((res) => {
        if (res && res.length > 0) {
          this.$api.environment
            .getCollectList(this.tab.id, res[0].value)
            .then((res) => {
              this.results = res;
            });
        }
      });
      this.$api.device.getLiveInfo().then((res) => {
        this.Quality = res.Quality;
        this.AQI = res.AQI;
        this.initAirQualityChart();
      });
    },
    initAirQualityChart() {
      if (!this.$refs.airQualityChart) {
        return;
      }

      const chart = echarts.init(this.$refs.airQualityChart);
      const option = {
        backgroundColor: "transparent",
        series: [
          {
            type: "gauge",
            radius: "100%",
            startAngle: 90,
            endAngle: -270,
            pointer: {
              show: false,
            },
            progress: {
              show: true,
              overlap: false,
              roundCap: true,
              clip: false,
              itemStyle: {
                color: {
                  type: "linear",
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color: "#00FFB9",
                    },
                    {
                      offset: 1,
                      color: "#007EFF",
                    },
                  ],
                },
              },
            },
            axisLine: {
              lineStyle: {
                width: 10,
                color: [[1, "rgba(0,150,255,0.1)"]],
              },
            },
            splitLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              show: false,
            },
            data: [
              {
                value: this.AQI,
                detail: {
                  show: false,
                },
              },
            ],
            detail: {
              show: false,
            },
            title: {
              show: false,
            },
          },
        ],
      };

      chart.setOption(option);
      this.airQualityChart = chart;
    },
    handleTabChange(tab) {
      this.tab = tab;
      this.getData(tab.name);
    },
  },
};
</script>
<style lang="scss" scoped>
.env-layout {
  padding: 0;
  height: 181px;
}
.environment-info {
  margin-bottom: 20px;
  border-radius: 4px;
  height: 227px;
  width: 100%;
  position: relative;
}

.env-main {
  width: 180px;
  height: 180px;
  padding-bottom: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  text-align: center;
  position: relative;
  .env-chart {
    position: relative;
    top: 10px;
    width: 110px;
    height:110px;
  }
  .env-chart-content {
    top: 40%;
    left: 50%;
  }
  .env-footer{
    position: relative;
    top: -10px;
  }
}
.env-grid {
  gap: 6px;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(2, 1fr);
  .env-item {
    border-radius: 0;
    border: none;
    justify-content: flex-start;
  }
  .item-content {
    text-align: left;
  }
  .item-icon {
    position: relative;
    top: 3px;
  }
  .env-label {
    margin-left: 5px;
  }
  .env-value {
    font-size: 12px;
    text-indent: 27px;
  }
}
</style>